<?php
class ImgModel
{
    public static function getPath($filename)
    {
        $root_path = ConfigParserLib::get('img', 'root_path');
        //$dir1 = substr($filename, 0, 2);
        //$dir2 = substr($filename, 2, 2);
        //@mkdir($root_path . $dir1 . '/' . $dir2 . '/', 0777, true);
        //return $root_path . $dir1 . '/' . $dir2 . '/' . substr($filename, 4);
        return $root_path . $filename;
    }
    
    public function getFile($want_filename)
    {
        try
        {
            $tmp = explode('-', $want_filename);
            //http://www.imagemagick.org/script/command-line-options.php#quality
            //http://zlib.net/manual.html
            //jpg 质量1到100。当大于90时色彩通道不压缩。质量100时比原图大，质量75时也可能比原图大。有软件能把jpg压缩到很小，使用别的软件编辑会再次变大。todo
            //png 质量/10 = zlib压缩等级0-9，质量%10 = 排列算法0-9，所以90与80的效果相同，因为都是无损，90的体积会小点。
            //JPEG-2000 todo
            if($tmp[1] > 100)
            {
                throw new Exception();
            }
            $quality = $tmp[1];
            $tmp2 = explode('.', $tmp[2]);
            $original_filename = $tmp[0] . '.' . $tmp2[1];
            $tmp3 = explode('x', $tmp2[0]);
            $want_size = array
            (
                'width' => $tmp3[0] == 'auto' ? 0 : $tmp3[0],
                'height' => $tmp3[1] == 'auto' ? 0 : $tmp3[1],
            );
            $thumb = new Imagick(self::getPath($original_filename));
            $thumb->setImageCompressionQuality ($quality);
            $thumb->resizeImage($want_size['width'], $want_size['height'], Imagick::FILTER_LANCZOS,1);
            $thumb->writeImage(self::getPath($want_filename));
            return $thumb->getImageMimeType();
        }
        catch (ImagickException $e)
        {
            throw new Exception();
        }
    }
}
?>
